//
//  LoginViewController.m
//  SportsSocial
//
//  Created by yull on 14/10/29.
//  Copyright (c) 2014年 yull. All rights reserved.
//

#import "LoginViewController.h"
#import "UIView+Frame.h"
#import "LoginTextField.h"
#import "LoginRegistNet.h"
#import "UIViewController+RESideMenu.h"
#import "RESideMenu.h"
#import "LeftSideViewController.h"
#import "UserIMNet.h"
#import "UIColor+MethodExt.h"
#import "UserNet.h"
@interface LoginViewController ()

@property (nonatomic, strong) LoginTextField *accountTextField;

@property (nonatomic, strong) LoginTextField *passwordTextField;

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.navigationBarHidden = YES;
    
    UIImageView *backgroundImageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
    backgroundImageView.image = [UIImage imageNamed:@"left_bg"];
    [self.view addSubview:backgroundImageView];
    
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(5, Statebar_Height + 7, 40, 40);
    [backButton setImage:[UIImage imageNamed:@"btn_back_normal"] forState:UIControlStateNormal];
    [backButton setImage:[UIImage imageNamed:@"btn_back_pressed"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(onBackButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backButton];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(20, 100, self.view.width-40, 0.5)];
    lineView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:lineView];
    
    self.accountTextField = [[LoginTextField alloc] initWithFrame:CGRectMake(20, lineView.bottom, self.view.width - 40, 60)];
    NSDictionary *dict = @{NSForegroundColorAttributeName:RGB(221.0f, 145.0f, 130.0f),
                           NSFontAttributeName:[UIFont boldSystemFontOfSize:18.0f]};
    
    self.accountTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入账号" attributes:dict];
    
    UIImageView *accountImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"leftbar_user"]];
    self.accountTextField.leftView = accountImageView;
    self.accountTextField.leftViewMode = UITextFieldViewModeAlways;
    [self.view addSubview:self.accountTextField];
    
    lineView = [[UIView alloc] initWithFrame:CGRectMake(20, self.accountTextField.bottom, self.view.width-40, 0.5)];
    lineView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:lineView];
    
    self.passwordTextField = [[LoginTextField alloc] initWithFrame:CGRectMake(20, lineView.bottom, self.view.width - 40, 60)];
    self.passwordTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入密码" attributes:dict];
    self.passwordTextField.secureTextEntry = YES;
    
    UIImageView *passwordImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"leftbar_password"]];
    self.passwordTextField.leftView = passwordImageView;
    self.passwordTextField.leftViewMode = UITextFieldViewModeAlways;
    [self.view addSubview:self.passwordTextField];

    lineView = [[UIView alloc] initWithFrame:CGRectMake(20, self.passwordTextField.bottom, self.view.width-40, 0.5)];
    lineView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:lineView];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(40, lineView.bottom + 20, self.view.width - 80, 40);
    button.layer.borderColor = [[UIColor whiteColor] CGColor];
    button.layer.borderWidth = 1.0f;
    button.layer.cornerRadius = 5.0f;
    [button setTitle:@"登陆" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(onLoginButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    
//    self.accountTextField.text = @"18910712342";
//    self.passwordTextField.text = @"1";
}

- (void)onLoginButton:(id)sender
{
    self.textProgressHUD.mode = MBProgressHUDModeIndeterminate;
    [self showText:@"正在登陆..." time:9999];
    
    [self.view endEditing:YES];
    [LoginRegistNet loginWithName:self.accountTextField.text password:self.passwordTextField.text successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        [self.textProgressHUD hide:NO];
        self.textProgressHUD.mode = MBProgressHUDModeText;
        BOOL success = [[responseObject objectForKey:@"success"] boolValue];
        if (success) {
            NSDictionary *dataDict = [responseObject objectForKey:@"data"];
            CurrentUser *currentUser = [CurrentUser shareInstance];
            [currentUser updateWithDict:dataDict];
            currentUser.isLogin = YES;
            
            [[UserIMNet shareInstance] login];
            
            [UserNet updateIOSdeviceTokenSuccessBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
                NSLog(@"devicetoken更新成功！");
            } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
                NSLog(@"devicetoken更新失败！");
            }];
            
            [[DBManager shareInstance] openDataBaseByUserId:[CurrentUser shareInstance].userId];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"ChatInfoReload" object:nil];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                LeftSideViewController *leftSideViewControlelr = (LeftSideViewController *)self.sideMenuViewController.leftMenuViewController;
                [leftSideViewControlelr handleLoginSuccess];
                [self.navigationController popViewControllerAnimated:YES];
                self.navigationController.navigationBarHidden = NO;
            });
        } else {
            NSString *message = [responseObject objectForKey:@"message"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:message time:2];
            });
        }
        
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self.textProgressHUD hide:NO];
        self.textProgressHUD.mode = MBProgressHUDModeText;
        [[NSNotificationCenter defaultCenter] postNotificationName:@"ChatInfoReload" object:nil];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self showText:@"网络连接失败" time:2];
        });
    }];
}

- (void)onBackButton:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
